<template>
    <div class="attr">
        <Category :scene="scene" />

        <div v-show="scene === 0">
            <el-button
                type="primary"
                icon="plus"
                :disabled="categoryStore.c3Id === ''"
                @click="handleAddAttr"
            >
                添加属性
            </el-button>

            <el-table border class="table" :data="attrArr">
                <el-table-column label="序号" type="index" width="80px" />
                <el-table-column label="属性名称" width="120px" prop="attrName" />
                <el-table-column label="属性值名称">
                    <template #default="{ row }">
                        <el-tag
                            type="primary"
                            style="margin: 5px"
                            v-for="item in row.attrValueList"
                            :key="item.attrId"
                        >
                            {{ item.valueName }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180px">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="handleEditAttr(row)">
                            编辑
                        </el-button>
                        <el-popconfirm
                            :title="`您确定要删除 ${row.attrName} 吗？`"
                            width="230px"
                            @confirm="handleDeleteAttr(row)"
                        >
                            <template #reference>
                                <el-button type="danger" size="small">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div v-show="scene === 1">
            <el-form :inline="true">
                <el-form-item label="属性名称">
                    <el-input
                        v-model="attrParams.attrName"
                        placeholder="请你输入属性名称"
                    ></el-input>
                </el-form-item>
            </el-form>

            <el-button
                type="primary"
                icon="plus"
                :disabled="attrParams.attrName.length === 0"
                @click="handleAddAttrValue"
            >
                添加属性值
            </el-button>
            <el-button type="primary" @click="handleCancel">取消</el-button>

            <el-table border :data="attrParams.attrValueList" class="table">
                <el-table-column label="序号" type="index" align="center" width="80px" />
                <el-table-column label="属性值名称">
                    <template #default="{ row, $index }">
                        <el-input
                            @blur="toLook(row, $index)"
                            v-model="row.valueName"
                            placeholder="请你输入属性值名称"
                            size="small"
                            v-if="row.flag"
                            :ref="(el: any) => (inputArr[$index] = el)"
                        ></el-input>
                        <div v-else @click="toEdit(row, $index)">
                            {{ row.valueName }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="属性值操作">
                    <template #default="{ row, $index }">
                        <el-popconfirm
                            :title="`您确定要删除 ${row.valueName} 吗？`"
                            width="230px"
                            @confirm="handleDeleteAttrValue($index)"
                        >
                            <template #reference>
                                <el-button type="danger" size="small">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>

            <el-button
                type="primary"
                :disabled="attrParams.attrValueList.length === 0"
                @click="handleSaveAttrValue"
            >
                保存
            </el-button>
            <el-button type="primary" @click="handleCancel">取消</el-button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, reactive, nextTick, onBeforeUnmount } from 'vue'
import type { Attr, AttrValue } from '@/api/product/attr/type'
import { useCategoryStore } from '@/store/modules/category'
import { reqAttr, reqAddOrUpdateAttr, reqRemoveAttr } from '@/api/product/attr'
import { ElMessage } from 'element-plus'

const categoryStore = useCategoryStore()

const attrArr = ref<Attr[]>([])

watch(
    () => categoryStore.c3Id,
    () => {
        attrArr.value = []
        if (!categoryStore.c3Id) return
        getAttr()
    },
)

const getAttr = async () => {
    const { c1Id, c2Id, c3Id } = categoryStore
    const result = await reqAttr(c1Id, c2Id, c3Id)
    if (result.code === 200) {
        attrArr.value = result.data
    }
}

const attrParams = reactive<Attr>({
    attrName: '',
    attrValueList: [],
    categoryId: '',
    categoryLevel: 3,
})

const scene = ref<number>(0)

const handleAddAttr = () => {
    Object.assign(attrParams, {
        attrName: '',
        attrValueList: [],
        categoryId: categoryStore.c3Id,
        categoryLevel: 3,
    })

    scene.value = 1
}

const handleCancel = () => {
    scene.value = 0
}

const handleAddAttrValue = () => {
    attrParams.attrValueList.push({
        valueName: '',
        flag: true,
    })

    nextTick(() => {
        inputArr.value[attrParams.attrValueList.length - 1].focus()
    })
}

const toLook = (row: AttrValue, $index: number) => {
    // 1. 当什么都没有输入时，提示不合法
    if (row.valueName.trim().length === 0) {
        ElMessage.error('请输入属性值名称')
        attrParams.attrValueList.splice($index, 1)
        return
    }

    // 2. 判断是否存在重复录入的属性值
    const isExist = attrParams.attrValueList.some(
        item => item !== row && item.valueName === row.valueName,
    )

    if (isExist) {
        ElMessage.error('属性值名称不能重复')
        attrParams.attrValueList.splice($index, 1)
        return
    }
    row.flag = false
}

const toEdit = (row: AttrValue, $index: number) => {
    row.flag = true
    nextTick(() => {
        inputArr.value[$index].focus()
    })
}

const handleDeleteAttrValue = ($index: number) => {
    attrParams.attrValueList.splice($index, 1)
}

const handleSaveAttrValue = () => {
    const result: any = reqAddOrUpdateAttr(attrParams)
    if (result.code === 200) {
        const msg = attrParams.id ? '更新成功' : '添加成功'
        ElMessage.success(msg)
        scene.value = 0
        getAttr()
    } else {
        const msg = attrParams.id ? '更新失败' : '添加失败'
        ElMessage.error(msg)
    }
}

const inputArr = ref<any>([])

const handleEditAttr = (row: any) => {
    scene.value = 1
    Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}

const handleDeleteAttr = (row: any) => {
    const result: any = reqRemoveAttr(row.id)
    if (result.code === 200) {
        ElMessage.success('删除成功')
        getAttr()
    } else {
        ElMessage.error('删除失败')
    }
}

onBeforeUnmount(() => {
    categoryStore.$reset()
})
</script>

<style lang="scss" scoped>
.attr {
    .category {
        margin-bottom: 20px;
        border-bottom: 1px solid #e4e7ed;
    }

    .table {
        margin: 20px 0;
    }
}
</style>
